package org.thread.test05.syn.demo03;

import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author CSY
 * @date 2025 - 03 - 11
 */
public class MyRunnable implements Runnable {

    /**
     * 总票数
     */
    private Integer ticketCount;

    private ReentrantLock reentrantLock = new ReentrantLock();

    public MyRunnable() {
    }

    public MyRunnable(Integer ticketCount) {
        this.ticketCount = ticketCount;
    }

    @Override
    public void run() {
        while (true) {
            try{
                //从这段开始锁住
                reentrantLock.lock();
                Integer sellCount = new Random().nextInt(1, 10);
                if (ticketCount == 0) {
                    System.out.println(Thread.currentThread().getName() + "没票了，停止售票");
                    break;
                }
                if (sellCount <= ticketCount) {
                    ticketCount -= sellCount;
                    System.out.println(Thread.currentThread().getName() + "成功出售" + sellCount + "张票，剩余：" + ticketCount);
                } else {
                    sellCount = ticketCount;
                }
            }finally{
                //解锁
                reentrantLock.unlock();
            }
        }
    }
}
